<template>
    <div ref="scrollview" class="page">
        <Header title="竞价投放" left-arrow />
        <div class="title">
            请设置您的竞价策略
        </div>
        <template v-for="item in strategyList" :key="item.uid">
            <StrategyCard :data="item" :index="item.uid" @del="del" @change="change" @focus="focus" @blur="blur" />
        </template>
        <div class="add" @click="add">
            +新增城市策略
        </div>
        <footer ref="footRef" class="footer">
            <div class="case">
                <div>
                    <div class="label">
                        每周总预算(元)
                    </div>
                    <div class="value">
                        {{ formatNumber(totalPrice) }}
                    </div>
                </div>
                <div>
                    <div class="label">
                        投放城市(个)
                    </div>
                    <div class="value">
                        {{ totalCity.length }}
                    </div>
                </div>
                <div>
                    <div class="label">
                        预估最多竞得点位(个)
                    </div>
                    <div class="value">
                        {{ totalPoint }}
                    </div>
                </div>
            </div>
            <div class="tips">
                <span class="icon iconfont icon-tishi"></span>
                <span>实际竞得点位以平台竞价结果为准，每周竞价结束后提供竞价结果</span>
            </div>
            <Button type="primary" block :disabled="strategyList.length === 0" @click="bid">
                开始竞价
            </Button>
            <div class="van-safe-area-bottom"></div>
        </footer>
        <city-area-selecter
            :show="showCityPicker"
            :list="formData.cityList"
            :selected="formData.cityCodeList"
            @close="showCityPicker = false"
            @confirm="onCityConfirm"
        />
    </div>
</template>

<script name="productsBidStrategyCheck" lang="ts" setup>
import { ref, reactive } from 'vue';
import { store } from '@/store';
import { useRouter } from 'vue-router';
import StrategyCard from './strategyCard.vue';
import { Button, Toast } from 'vant';
import Header from '@/components/Header/index.vue';
import CityAreaSelecter from '@/components/CityAreaSelecter/index.vue';
import { getCityTreeData } from '@/api/common';
import { executeBid } from '@/api/bid';
import { TreeChildModel, ReturnData } from '@/components/CityAreaSelecter/city.module';
import { formatNumber } from '@/utils/filters';

const router = useRouter();

const projectId: string = store.state.app.home.projectId || '';
const cityList = JSON.parse((router.currentRoute.value.params.cityList || '[]') as unknown as string) as [];

const showCityPicker = ref<boolean>(false);

const totalPrice = ref(0);
const totalCity = ref([]);
const totalPoint = ref(0);

interface Strategy{
    budget: number;
    maxBidPoint: number;
    name: string;
    uid: string;
    id: string;
}

cityList.map((item: Strategy, index) => {
    item.uid = `${item.id}${index}`;
});
const strategyList = ref<Strategy[]>([...cityList]);

const reset = () => {
    totalPrice.value = 0;
    totalCity.value = [];
    totalPoint.value = 0;
};

const calcTotal = () => {
    reset();
    strategyList.value.map((item: Strategy) => {
        totalPrice.value += Number(item.budget as unknown as number || 0);
        totalPoint.value += Number(item.maxBidPoint || 0);
        if (!totalCity.value.includes(item.name as never)) {
            totalCity.value.push(item.name as never);
        }
    });
};

interface FormData{
    cityList: TreeChildModel[];
    cityCodeList: string[];
}

const formData: FormData = reactive({
    cityList: [],
    cityCodeList: [],
});

const add = async () => {
    try {
        formData.cityList = await getCityTreeData(0);
    } catch (error) {
        formData.cityList = [];
    }
    showCityPicker.value = true;
};

const del = (uid: string) => {
    strategyList.value = strategyList.value.filter((item: Strategy) => {
        return item.uid !== uid;
    });
    calcTotal();
};

const change = (val: object, uid: string) => {
    const obj = strategyList.value.find(item => item.uid === uid);
    Object.assign(obj, val);
    calcTotal();
};

const footRef = ref<HTMLElement | null>(null);
const focus = (e: FocusEvent) => {
    if (footRef.value) {
        footRef.value.style.display = 'none';
    }
    if (e) {
        const tar = e.currentTarget as HTMLInputElement;
        if (!tar) {
            return;
        }
        // tar.style.scrollMarginTop = '300px';
        tar.scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'nearest'
        });
    }
};

const blur = () => {
    if (footRef.value) {
        footRef.value.style.display = 'block';
    }
};

interface StrategyItemData{
    cityCode: string;
    budget: number;
    bidPrice: number;
    mediaType: number;
    duration: string;
    frequency: string;
    maxBidPoint: number;
}

const bid = async () => {
    if (strategyList.value.length === 0) {
        Toast.fail('请添加竞价策略');
        return;
    }
    try {
        let params = strategyList.value.map((item: StrategyItemData) => {
            return {
                cityCode: item.cityCode,
                budget: item.budget,
                bidPrice: item.bidPrice,
                mediaType: item.mediaType,
                duration: item.duration,
                frequency: item.frequency,
                maxBidPoint: item.maxBidPoint,
            };
        });
        params = params.filter((item: StrategyItemData) => {
            return typeof item.cityCode !== 'undefined';
        });

        if (params.length === 0) {
            Toast.fail('请至少选择一个有点位的城市');
            return;
        }

        const res = await executeBid(params, projectId);
        if (res) {
            await router.push({
                name: 'productsBidReport',
                params: {
                    data: JSON.stringify(res),
                },
            });
        }
    } catch (error) {
        console.log(error);
    }
};

const onCityConfirm = (value: ReturnData) => {
    strategyList.value = strategyList.value.concat(value.checkedData as never);
    strategyList.value.map((item: Strategy, index) => {
        item.uid = `${item.id}${index}`;
    });
    calcTotal();
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables";

.page {
    box-sizing: border-box;
    padding: 12px;
    background: #f4f4f4;
    min-height: calc(100vh - 50px);
    height: calc(100vh - 50px);
    overflow: scroll;
}
.title {
    margin: 4px 0 16px;
    font-weight: 600;
    font-size: 16px;
    color: #333333;
}
.add {
    text-align: center;
    color: #397ff8;
    font-weight: 400;
    font-size: 14px;
    margin-bottom: 160px;
}
.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 6px 12px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0 -2px 4px 0 #ebebeb80;
    z-index: 1;
    .van-button {
        height: 38px;
        line-height: 38px;
        background: #e60044;
        border-radius: 6px;
        border: 0;
    }
    .case {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 6px 0 12px;
        .label {
            font-weight: 400;
            font-size: 12px;
            color: #5b5b5b;
        }
        .value {
            font-family: $spec_font;
            font-size: 18px;
            color: #e60044;
        }
    }
    .tips {
        font-weight: 400;
        font-size: 12px;
        color: #b5b5b5;
        letter-spacing: 0;
        margin-bottom: 12px;
        display: flex;
        .icon-tishi {
            width: 14px;
            height: 14px;
            margin: 2px 8px 0 0;
        }
    }
}
</style>
